import { app } from "electron"
import { autoUpdater, ProgressInfo } from "electron-updater"
import { exit } from "process"
const { dialog, BrowserWindow } = require('electron')

const path = require('path')
const os = require('os')
const ProgressBar = require('electron-progressbar')

const isDevelopment = process.env.NODE_ENV === 'development'

// 防止报错no such file or directory dev-app-update.yml
console.log('isDevelopment',isDevelopment,path.join(__dirname, '../dev-app-update.yml'))
if (isDevelopment) {
    autoUpdater.updateConfigPath = path.join(__dirname, '../dev-app-update.yml')
}

export default (checkResult?:(res:boolean)=>void,onDownload?:(progress:ProgressInfo)=>void) => {

	let progressBar

	autoUpdater.setFeedURL('https://xiaobaozi-1252810292.cos.ap-chengdu.myqcloud.com/test/')

    //设置自动下载
    autoUpdater.autoDownload = false

    // 检测是否有新版本
    autoUpdater.checkForUpdates()

	if(!app.isPackaged){
		console.log("跳过版本检查")
		checkResult(false)
	}
	
	//@ts-ignore
    autoUpdater.on('checking-for-update', res => {
        console.log("获取版本信息:" + res)
    })

	autoUpdater.on('error', res => {
        console.log("获取版本错误:" + res)
		checkResult(false)
    })

    autoUpdater.on('update-not-available', res => {
        console.log("没有可更新版本:" + res)
		if(checkResult)checkResult(false)
    })

    autoUpdater.on('update-available', res => {
		if(checkResult)checkResult(true)
        dialog.showMessageBox({
            type: 'info',
            title: '软件更新',
            message: '发现新版本, 确定更新?',
            buttons: ['确定', '取消'],
			defaultId:0,
			cancelId:2
        }).then(resp => {
            if (resp.response == 0) {
                autoUpdater.downloadUpdate()
				progressBar = new ProgressBar({
					indeterminate:false,
					maxValue:100,
					title:'更新',
					text: '正在下载更新包',
					detail: '请稍候...',
					style:{
						text:{
							overflow:'hidden'
						}
					}
				});
				progressBar
				.on('completed', function() {
					progressBar.detail = '安装包下载完成';
				})
				.on('aborted', function(value) {
					console.info(`aborted... ${value}`);
				})
				.on('progress', function(value) {
					progressBar.detail = `下载进度：${value}%`;
				});
            }
			if (resp.response == 1||resp.response == 2) {
                app.quit()
				exit(0)
            }
        })
    })

    autoUpdater.on('download-progress', res => {
        console.log("下载监听:" + res)
		progressBar.value=Number(res.percent.toFixed(2))
		onDownload?.call(res)
        // win.webContents.send('downloadProgress', res)
    })

    autoUpdater.on('update-downloaded', () => {
		progressBar.setCompleted()
        dialog.showMessageBox({
            title: '下载完成',
            message: '最新版本已下载完成, 退出程序进行安装'
        }).then(() => {
			const electron = require('electron');
			const app = electron.app;
			const BrowserWindow = electron.BrowserWindow;
			app.removeAllListeners('window-all-closed');
			var browserWindows = BrowserWindow.getAllWindows();
			browserWindows.forEach(function(browserWindow) {
				browserWindow.removeAllListeners('close');
			});
            autoUpdater.quitAndInstall()
        })
    })
}